<?php

class Crsf {

	private $memcahe;

	//用户id
	private $id;

	public function __construct(Memcache $memcache, $id) {
		$this->memcahe = $memcache;
		$this->id      = $id;
	}

	/**
	 * 设置token
	 */
	public function set() {
		$token = md5(uniqid(mt_rand(1,10000),1));
		$this->memcahe->set('crsf_token_' . $this->id, $token);
		return $token;
	}

	/**
	 * 检测token
	 * @param $reques_token
	 * @return bool
	 */
	public function check($reques_token) {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			if ($this->get() != $reques_token) {
				return false;
			}
		}
		return true;
	}


	/**
	 * 获取token
	 * @return array|string
	 */
	private function get() {
		return $this->memcahe->get('crsf_token_' . $this->id);
	}

}

$uid = 1;

$memcache_handle = new Memcache();

$crsf = new Crsf($memcache_handle, $uid);

//检测token是否正确
if ($crsf->check($_REQUEST['csrf_token']) == false) {
	throw new ErrorException('crsf_token 验证失败');
}

//设置并分配一个新token
$this->assign('crsf_token',$crsf->set());
